
import pymysql
from pyecharts.charts import Pie
from pyecharts import options

db = pymysql.connect(
    host="localhost",
    user="root",
    password="222700360Wlq",
    database="crawlerdemo",
    charset="utf8"
)
cursor = db.cursor()
sql = "select job_place, count(job_id) from job group by job_place order by count(job_id) desc limit 5"
try:
    cursor.execute(sql)
    res = cursor.fetchall()
    total_jobs = sum([row[1] for row in res])
    data = [(row[0], round((row[1] / total_jobs) * 100, 2)) for row in res]
    pie = Pie()
    pie.add("岗位占比", data)
    pie.set_global_opts(
        title_opts=options.TitleOpts(title="岗位数量最多的五个城市的占比"),
        legend_opts=options.LegendOpts(is_show=False)
    )
    pie.set_series_opts(
        label_opts=options.LabelOpts(formatter="{b}: {d}%")
    )
    pie.render("piera.html")
except:
    print("查询出错啦")
finally:
    cursor.close()
    db.close()